package com.thinkit.bigdata.web.controller.bus;

import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.FileUtil;
import com.thinkit.bigdata.core.util.FtpUtil;
import com.thinkit.bigdata.core.util.ProjectPubMet;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.BusVoiceDetails;
import com.thinkit.bigdata.web.model.bus.BusVoiceDetailsSearch;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.bus.BusVoiceDetailsService;
import com.thinkit.bigdata.web.service.sys.SysConfigService;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.util.Date;

@RestController
@RequestMapping("/voice")
public class BusVoiceDetailsController {

    private static Logger logger = Logger.getLogger(BusVoiceDetailsController.class);

    private static String VOICE_LOG_MES = "【话单详情导出数据任务】";

    @Resource
    private BusVoiceDetailsService detailsService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private ProjectPubMet pubMet;

    @RequestMapping(value = "/get-voice-by-pessim", method = RequestMethod.POST)
    public HtmlResult voiceListByPessim(
            @RequestParam(value = "provinceCode") final String provinceCode,
            @RequestParam(value = "dataCode") final String dataCode
    ) {
        logger.info(VOICE_LOG_MES + "按照登陆人查询各自的创建的全部任务");
        return detailsService.voiceListByPessim(provinceCode, dataCode);
    }

    @RequestMapping(value = "/get-voice-by-page", method = RequestMethod.POST)
    public HtmlResult voiceListByPage(@RequestBody BusVoiceDetailsSearch search) {
        logger.info(VOICE_LOG_MES + "分页查询");
        logger.info(VOICE_LOG_MES + "search = " + search.toString());
        return detailsService.selectByExample(search);
    }

    @RequestMapping(value = "/add-voice", method = RequestMethod.POST)
    public HtmlResult addVoice(@RequestBody BusVoiceDetails detail) {
        logger.info(VOICE_LOG_MES + "添加");
        logger.info(VOICE_LOG_MES + "dto = " + detail.toString());
        try {
            return detailsService.insert(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure("添加异常");
        }
    }

    @RequestMapping(value = "/add-5G", method = RequestMethod.POST)
    public HtmlResult add5G(
            @RequestParam(value = "dataCode") final String dataCode,
            @RequestParam(value = "provinceCode") final String provinceCode,
            @RequestParam(value = "callTags") final String callTags,
            @RequestParam(value = "scene") final String scene,
            @RequestParam(value = "callStartTime") final String callStartTime,
            @RequestParam(value = "callEndTime") final String callEndTime
    ) {
        logger.info(VOICE_LOG_MES + "添加");
        logger.info(VOICE_LOG_MES + "dataCode = " + dataCode);
        logger.info(VOICE_LOG_MES + "provinceCode = " + provinceCode);
        logger.info(VOICE_LOG_MES + "callTags = " + callTags);
        logger.info(VOICE_LOG_MES + "scene = " + scene);
        logger.info(VOICE_LOG_MES + "callStartTime = " + callStartTime);
        logger.info(VOICE_LOG_MES + "callEndTime = " + callEndTime);
        try {
            return detailsService.insert5G(dataCode, provinceCode, callTags,  scene, callStartTime, callEndTime);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return HtmlResult.failure("添加异常");
        }
    }

    @RequestMapping(value = "/update-voice", method = RequestMethod.POST)
    public HtmlResult updateVoice(@RequestBody BusVoiceDetails detail) {
        logger.info(VOICE_LOG_MES + "修改");
        logger.info(VOICE_LOG_MES + "dto = " + detail.toString());
        try {
            return detailsService.updateByPrimaryKey(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure("修改异常");
        }
    }

    @RequestMapping(value = "/del-voice", method = RequestMethod.POST)
    public HtmlResult delVoice(@RequestParam(value = "ids") final String ids) {
        logger.info(VOICE_LOG_MES + "删除");
        logger.info(VOICE_LOG_MES + "ids = " + ids);
        return detailsService.deleteByPrimaryKey(ids);
    }

    @RequestMapping(value = "/export-file-task", method = RequestMethod.POST)
    public void exportFileTask(@RequestParam(value = "id") final Long id, HttpServletResponse response) {
        try {
            logger.info(VOICE_LOG_MES + "下载导出的文件操作");
            logger.info(VOICE_LOG_MES + "id = " + id);
            String resultStr = null;
            BusVoiceDetails detail = detailsService.selectByPrimaryKey(id);
            int textMaxHour = Integer.parseInt(sysConfigService.sysConfigGetByPK(Constants.TEXT_MAX_HOUR).getValue());
            Date invalidTime = DateFormatUtil.addMinute(detail.getFinishtime(), (textMaxHour * 60));
            if (DateFormatUtil.intervalSecond(invalidTime,  new Date()) > 0) {
                resultStr = "文件已经过期！";
                logger.info(VOICE_LOG_MES + "即时修改状态为过期");
                detail.setIsdel(BaseEntity.FILE_IS_DEL_YES);
                String log = detailsService.updateByPrimaryKey(detail).getCode() == 0 ? "状态修改失败" : "状态修改成功";
                logger.info(VOICE_LOG_MES + log);
            } else {
                //登陆ftp
                FtpUtil ftpUtil = pubMet.getFtpUtil();
                String localPath = SystemStatic.SYSTEM_USER_PATH_EXPORT + detail.getFilename();
                //从ftp获取到本地
                if (!ftpUtil.downloadFile(detail.getFilepath(), localPath)) {
                    throw new RuntimeException();
                }
                //关闭ftp链接
                ftpUtil.disconnect();
                File file = new File(localPath);
                FileUtil.downloadFile(file, response);
                FileUtil.deleteFile(file);
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(resultStr);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
